package com.lishe.lishe.lishe.module.shopingcart.adapter;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.event.RefreshShopCarCountEvent;
import com.lishe.lishe.lishe.module.mall.activity.GoodsDetailActivity;
import com.lishe.lishe.lishe.module.shopingcart.bean.ShopCarBean;
import com.lishe.lishe.lishe.module.shopingcart.bean.UpdateCountBean;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.lishe.utils.ViewUtils;
import com.lishe.lishe.net.BaseHttpLoader;
import com.lishe.lishe.net.BaseProtocal;
import com.lishe.lishe.net.NetAPI;
import com.lishe.lishe.net.ResultListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.Observable;
import okhttp3.ResponseBody;

/**
 * Created by Bin
 */
public class ShoppingCarAdapter extends BaseExpandableListAdapter {

    private Activity mContext;
    private CheckListener mCheckListener;
    private List<ShopCarBean.DataBean> mList;

    public interface CheckListener {
        void onCheck();
    }

    public void setCheckListener(CheckListener listener) {
        mCheckListener = listener;
    }

    public ShoppingCarAdapter(Activity context, List<ShopCarBean.DataBean> list) {
       this.mContext = context;
       this.mList = list;
    }

    /**
     * 购物车全选
     */
    public void checkAll(boolean isCheckAll) {
        for (int i = 0; i < mList.size(); i++) {
            mList.get(i).isCheck = isCheckAll;
            for (int j = 0; j < mList.get(i).goodsInfo.size(); j++) {
                mList.get(i).goodsInfo.get(j).isCheck = isCheckAll;
            }
        }
        notifyDataSetChanged();
        mCheckListener.onCheck();
    }

    // 获取组的个数
    @Override
    public int getGroupCount() {
        return mList.size();
    }

    // 获取指定组中的子元素个数
    @Override
    public int getChildrenCount(int groupPosition) {
        return mList.get(groupPosition).goodsInfo.size();
    }

    // 获取指定组中的数据
    @Override
    public Object getGroup(int groupPosition) {
        return mList.get(groupPosition);
    }

    // 获取指定组中的指定子元素数据
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mList.get(groupPosition).goodsInfo.get(childPosition);
    }

    // 获取指定组的ID，这个组ID必须是唯一的
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    // 获取指定组中的指定子元素ID
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    // 组和子元素是否持有稳定的ID,也就是底层数据的改变不会影响到它们
    @Override
    public boolean hasStableIds() {
        return true;
    }

    // 获取显示指定组的视图对象
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder holder;
        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_shopcar_group, null);
            holder = new GroupViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (GroupViewHolder) convertView.getTag();
        }

        holder.shopName.setText(mList.get(groupPosition).shop_name);
        if (mList.get(groupPosition).isCheck) {
            holder.checkImg.setImageResource(R.mipmap.sel_check_icon);
        } else {
            holder.checkImg.setImageResource(R.mipmap.nor_check_icon);
        }
        holder.checkArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isCheck = mList.get(groupPosition).isCheck;
                mList.get(groupPosition).isCheck = !isCheck;
                // 店铺内商品选中处理
                if (mList.get(groupPosition).isCheck) {
                    for (int i = 0; i < mList.get(groupPosition).goodsInfo.size(); i++) {
                        mList.get(groupPosition).goodsInfo.get(i).isCheck = true;
                    }
                } else {
                    for (int i = 0; i < mList.get(groupPosition).goodsInfo.size(); i++) {
                        mList.get(groupPosition).goodsInfo.get(i).isCheck = false;
                    }
                }
                notifyDataSetChanged();
                mCheckListener.onCheck();
            }
        });
        return convertView;
    }

    // 获取一个视图对象，显示指定组中的指定子元素数据
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder holder;
        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_shopping_car_goods, null);
            holder = new ChildViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (ChildViewHolder) convertView.getTag();
        }
        ShopCarBean.DataBean.GoodsInfoBean bean = mList.get(groupPosition).goodsInfo.get(childPosition);
        holder.goodsName.setText(bean.title);
        holder.goodsInfo.setText(bean.spec_info);
        ImageLoaderUtils.displayImage(mContext, bean.image_default_id, holder.goodsImg);
        holder.money.setText("¥" + bean.price);
        holder.count.setText(bean.quantity + "");
        if (bean.quantity <= 1) {
            holder.redus.setBackgroundResource(R.mipmap.sub1);
        } else {
            holder.redus.setBackgroundResource(R.mipmap.sub);
        }

        if (bean.isCheck) {
            holder.checkImg.setImageResource(R.mipmap.sel_check_icon);
        } else {
            holder.checkImg.setImageResource(R.mipmap.nor_check_icon);
        }

        //点击商品跳到商品详情页
        holder.item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GoodsDetailActivity.jump(mContext, bean.item_id);
            }
        });

        //长按删除
        holder.item.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                new AlertDialog.Builder(mContext)
                        .setMessage("是否删除该商品？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                removeGoods(groupPosition, childPosition);
                            }
                        })
                        .create().show();
                return true;
            }
        });

        holder.checkArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bean.isCheck = !bean.isCheck;
                isGroupAllCheck(groupPosition);
                notifyDataSetChanged();
                mCheckListener.onCheck();
            }
        });

        ViewUtils.addTouch(holder.redusLayout, 100, 100, 100, 100);
        ViewUtils.addTouch(holder.augmentLayout, 100, 100, 100, 100);

        //减
        holder.redusLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bean.quantity <= 1) {

                } else {
                    updateCount(bean.cart_id, "dec", bean.quantity - 1, groupPosition, childPosition);
                }
            }
        });
        //加
        holder.augmentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateCount(bean.cart_id, "inc", bean.quantity + 1, groupPosition, childPosition);
            }
        });

        if (childPosition == 0) {
            holder.line.setVisibility(View.GONE);
        }else {
            holder.line.setVisibility(View.VISIBLE);
        }
        return convertView;
    }

    /**
     *  判断该店铺是否选中所有商品
     */
    public void isGroupAllCheck(int groupPosition) {
        boolean isAllCheck = true;
        for (int i = 0; i < mList.get(groupPosition).goodsInfo.size(); i++) {
            if (!mList.get(groupPosition).goodsInfo.get(i).isCheck) {
                isAllCheck = false;
                break;
            }
        }
        mList.get(groupPosition).isCheck = isAllCheck;
    }

    /**
     * 改变商品数量
     */
    private void updateCount(String cartId, String op, int count, int groupPositon, int childPosition) {
        LoadingUtils.createLoadingDialog(mContext, "加载中...", false);
        BaseHttpLoader http = new BaseHttpLoader(UpdateCountBean.class, Globals.LISHE_URL) {
            @Override
            public Observable<ResponseBody> structureObservable(NetAPI api) {
                return api.opCart(Globals.getToken(), cartId, op, count + "");
            }
        };
        http.executor(new ResultListener() {
            @Override
            public void onSuccess(BaseProtocal mBaseProtocal) {
                UpdateCountBean bean = (UpdateCountBean) mBaseProtocal;
                mList.get(groupPositon).goodsInfo.get(childPosition).quantity = bean.data.num;
                notifyDataSetChanged();
                mCheckListener.onCheck();
            }

            @Override
            public void onFail(int errcode, String msg) {
                ToastUtil.showToast(mContext, msg);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(mContext, R.string.network_or_server_exception);
            }
        });
    }

    /**
     * 从购物车把商品移除
     */
    private void removeGoods(int groupPosition, int childPosition) {
        LoadingUtils.createLoadingDialog(mContext, mContext.getString(R.string.delectiing), false);
        BaseHttpLoader http = new BaseHttpLoader(BaseProtocal.class, Globals.LISHE_URL) {
            @Override
            public Observable<ResponseBody> structureObservable(NetAPI api) {
                return api.delFromCart(Globals.getToken(), mList.get(groupPosition).goodsInfo.get(childPosition).cart_id);
            }
        };
        http.executor(new ResultListener() {
            @Override
            public void onSuccess(BaseProtocal mBaseProtocal) {
                EventBus.getDefault().post(new RefreshShopCarCountEvent());
                mList.get(groupPosition).goodsInfo.remove(childPosition);
                // 如果一个店铺没有商品 移除该店铺
                if (mList.get(groupPosition).goodsInfo.size() == 0) {
                    mList.remove(groupPosition);
                }
                notifyDataSetChanged();
                mCheckListener.onCheck();
            }

            @Override
            public void onFail(int errcode, String msg) {
                ToastUtil.showToast(mContext, msg);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(mContext, R.string.network_or_server_exception);
            }
        });
    }

    // 是否选中指定位置上的子元素
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    class GroupViewHolder {
        View checkArea;
        ImageView checkImg;
        TextView shopName;

        public GroupViewHolder(View view) {
            checkArea = view.findViewById(R.id.check_area);
            checkImg = view.findViewById(R.id.check_img);
            shopName = view.findViewById(R.id.shopname);
        }
    }

    class ChildViewHolder {
        View checkArea;
        ImageView checkImg;
        ImageView goodsImg;
        TextView goodsName;
        TextView goodsInfo;
        TextView money;
        View redus;
        View redusLayout;
        View augment;
        View augmentLayout;
        TextView count;
        View line;
        View item;

        public ChildViewHolder(View view) {
            checkArea = view.findViewById(R.id.img_area);
            checkImg = view.findViewById(R.id.check_img);
            goodsImg = view.findViewById(R.id.goods_img);
            goodsName = view.findViewById(R.id.goods_name);
            goodsInfo = view.findViewById(R.id.goods_info);
            money = view.findViewById(R.id.money);
            redus = view.findViewById(R.id.redus);
            redusLayout = view.findViewById(R.id.redus_layout);
            augment = view.findViewById(R.id.augment);
            augmentLayout = view.findViewById(R.id.augment_layout);
            count = view.findViewById(R.id.count);
            line = view.findViewById(R.id.bottom_line);
            item = view.findViewById(R.id.item);
        }
    }

}
